<template>
  <PageContainer>
    <view class="container">
      <Header
        v-model="headerHeight"
        :title="`${detailRef ? '编辑' : '创建'}表单`"
        :default-slot-content-height="160"
      >
        <template>
          <StepBar :current="stepBarCurrent" :list="stepBarList" />
        </template>
      </Header>
      <scroll-view
        v-if="isInit"
        class="action-area"
        :scroll-x="isScrollLoading"
        :scroll-y="true"
        scroll-with-animation
        enable-flex
        enable-passive
        paging-enabled
        bounces
        enhanced
        :show-scrollbar="false"
        :scroll-into-view="`scrollIntoView_${stepBarCurrent}`"
        :style="{
          height:
            stepBarCurrent !== 2
              ? `calc(100vh - ${headerHeight}px - ${buttonGroupHeight}px)`
              : `calc(100vh - ${headerHeight}px)`,
        }"
        @scroll="handleScroll"
      >
        <view class="action-area__item" id="scrollIntoView_0">
          <FormInfo v-if="stepBarCurrent === 0" ref="formInfoRef" :details="detailRef" />
        </view>
        <view class="action-area__item" id="scrollIntoView_1">
          <AddFormItem v-if="stepBarCurrent === 1" ref="addFormItemRef" :id="detailRef?.id" />
        </view>
        <view class="action-area__item" id="scrollIntoView_2">
          <FormSetting
            v-if="stepBarCurrent === 2"
            ref="formSettingRef"
            :details="detailRef"
            :posterPath="posterPath"
            @show-uni-popup="showUniPopup"
            @last-step="handlePreviousStep"
            @next-step="handleSubmit"
          />
        </view>
      </scroll-view>
      <view v-if="isScrollLoading" class="modal-view"></view>

      <TButtonGroup
        v-if="isInit && stepBarCurrent !== 2"
        v-model="buttonGroupHeight"
        :styles="{ backgroundColor: '#fff' }"
      >
        <TButton
          v-if="stepBarCurrent > 0"
          class="gutter-btn"
          text="上一步"
          type="none"
          custom-class="borderBtn"
          @click.stop="handlePreviousStep"
        />
        <TButton class="gutter-btn" text="下一步" type="primary" @click.stop="handleSubmit" />
      </TButtonGroup>
      <LPainter
        v-if="codeImg"
        isCanvasToTempFilePath
        :type="canvasType"
        path-type="url"
        @success="posterSuccess"
        @fail="posterFail"
        custom-style="position: fixed; left: 200%; top: 300rpx;"
        css="width: 400px; height: 538px;"
      >
        <LPainterView css="width: 400px; height: 538px; position: reactive;">
          <LPainterImage
            src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/obs/20240328/afa4a95b897a4dda99994fce65603f1b.png"
            css="width: 400px; height: 538px"
          />
          <LPainterView
            css="width: 360px; height: 498px; position: absolute; top: 0px; left: 0px; padding: 20px "
          >
            <LPainterImage :src="globalConfig?.logo" css="width:40px; height: 40px;" />
            <LPainterText
              css="color:#fff; text-align: center; margin-top: 6px; margin-left: 10px; font-size: 18px; font-weight: bold;"
              :text="globalConfig?.name"
            />
            <LPainterText
              css="width: 100%;color:#fff; text-align: center; font-size: 24px; font-weight: bold; margin-top: 30px; line-clamp: 2"
              :text="detailRef?.title"
            />
            <LPainterImage
              src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/obs/20240328/c9ab3dfb122e40a8a675f481e65ca88b.png"
              css="width:168px; height: 175px; margin: 0 auto; margin-top: 30px;"
            />
            <LPainterImage
              :src="codeImg"
              css="width:80px; height: 80px; margin: 0 auto; margin-top: 40px; border-radius: 50%"
            />
            <LPainterText
              css="width: 100%;color:#fff; text-align: center; font-size: 14px; margin-top: 8px; "
              text="扫码立即填写"
            />
          </LPainterView>
        </LPainterView>
      </LPainter>

      <UniPopup ref="sysUserPopup" :z-index="999" background-color="#fff" :is-mask-click="false">
        <view class="sysUser-popup">
          <view class="popup-title disFlxJS px-16 py-12">
            <text>表单管理员</text>
            <view class="ali-icon icon-guanbi1" @click="close"></view>
          </view>
          <view class="popup-warning disFlx px-16 py-10">
            <view class="ali-icon icon-tips"></view>
            <view>只可从系统管理员中选择，如需新增其他管理员，请前往【管理后台】新增管理员。</view>
          </view>
          <scroll-view
            scroll-y
            :enable-flex="true"
            scroll-with-animation
            scroll-anchoring
            :enhanced="true"
            :show-scrollbar="false"
            @scrolltolower="handleScrollToLower"
            class="pa-12 pb-0"
            style="height: 600rpx"
          >
            <Paglist
              v-model="sysUserListRef"
              :is-init-api="true"
              :isPullDownRefres="false"
              :parame="{
                current: 1,
                size: 10,
              }"
              @register="register"
              :is-show-loadmore="sysUserListRef.length > 1"
            >
              <template v-for="item in sysUserListRef" :key="item.systemUserId">
                <view class="px-16 py-12 disFlxAC fz-16" @click="changeChecked(item.systemUserId)">
                  <view class="pr-12 shrink0 check-box">
                    <view
                      v-if="tempSelected.includes(item.systemUserId)"
                      class="ali-icon icon-yixuan"
                      style="color: #2878ff"
                    ></view>
                    <view v-else class="ali-icon icon-fangxingweixuanzhong"></view>
                  </view>
                  <text>{{ item.userName }}</text>
                  <text class="ml-12">{{ item.phone }}</text>
                </view>
              </template>
            </Paglist>
            <!-- <view>
              <template v-for="item in sysUserListRef" :key="item.systemUserId">
                <view class="px-16 py-12 disFlxAC fz-16" @click="changeChecked(item.systemUserId)">
                  <view class="pr-12 shrink0 check-box">
                    <view
                      v-if="tempSelected.includes(item.systemUserId)"
                      class="ali-icon icon-yixuan"
                      style="color: #2878ff"
                    ></view>
                    <view v-else class="ali-icon icon-fangxingweixuanzhong"></view>
                  </view>
                  <text>{{ item.userName }}</text>
                  <text class="ml-12">{{ item.phone }}</text>
                </view>
              </template>
            </view> -->
          </scroll-view>
          <view class="px-16">
            <TButton
              class="gutter-btn"
              text="确认选择"
              type="primary"
              @click.stop="submitSelected"
            />
          </view>
        </view>
      </UniPopup>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* createServiceForm 创建表单 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
  import { navigateBack, onLoad, redirectTo } from '@/router';
  import { nextTick, provide, ref, unref, watch } from 'vue';
  import StepBar from '@/components/StepBar/index.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import FormInfo from './components/FormInfo.vue';
  import AddFormItem from './components/AddFormItem.vue';
  import FormSetting from './components/FormSetting.vue';
  import { type StepBarFormRef } from './components/refs';
  import {
    serviceTicketFormTemplateDetail,
    serviceTicketFormOpenSet,
    sysUserList,
  } from '@/api/serviceForm';
  import type {
    ServiceTicketFormTemplateDetailResult,
    ServiceTicketFormAddData,
    SysUserResult,
  } from '@/api/serviceForm/types';
  import { ServiceFormStatusEnum } from '@/enums/serviceFormEnum';
  import { createMiniCode } from '@/utils/dynamicConfig';
  import LPainter from '@/uni_modules/lime-painter/components/l-painter/l-painter.vue';
  import LPainterView from '@/uni_modules/lime-painter/components/l-painter-view/l-painter-view.vue';
  import LPainterImage from '@/uni_modules/lime-painter/components/l-painter-image/l-painter-image.vue';
  import LPainterText from '@/uni_modules/lime-painter/components/l-painter-text/l-painter-text.vue';
  import { useAppStore } from '@/store/modules/app';
  import { useUpload } from '@/hooks/core/useUpload';
  import { cloneDeep } from 'lodash-es';
  import Paglist from '@/components/Paglist/index.vue';
  import { useConList } from '@/components/Paglist/useConList';

  const { canvasType, globalConfig } = useAppStore();
  const { request } = useUpload();

  const headerHeight = ref(87);
  const buttonGroupHeight = ref(75);
  const formInfoRef = ref<StepBarFormRef | null>(null);
  const addFormItemRef = ref<StepBarFormRef | null>(null);
  const formSettingRef = ref<
    ({ submitSelected: (list: number[]) => void } & StepBarFormRef) | null
  >(null);

  const detailRef = ref<ServiceTicketFormTemplateDetailResult>();
  const isInit = ref(false);
  onLoad<'createServiceForm'>(async (op) => {
    const id = op.id;
    if (id) {
      const res = await serviceTicketFormTemplateDetail(id);
      detailRef.value = res;
    }
    stepBarCurrent.value = 0;
    isInit.value = true;
  });

  const codeImg = ref('');
  const posterPath = ref('');
  watch(
    detailRef,
    (nVal, oVal) => {
      if (nVal?.id || nVal?.title !== oVal?.title) {
        startDraw();
      }
    },
    { deep: true },
  );

  function startDraw() {
    createMiniCode({
      path: 'serviceFormFilling',
      query: {
        serviceTicketFormId: detailRef.value?.id,
      },
    }).then((res) => (codeImg.value = res));
  }

  const posterSuccess = (event: any) => {
    request('image', {
      tempFilePath: event as string,
      progress: 0,
    }).then((res) => {
      posterPath.value = res.imagePathBig as string;
    });
  };

  const posterFail = (err: any) => {
    console.log('posterFail', err);
  };

  const sysUserPopup = ref<UniPopupRef>();
  const open = () => unref(sysUserPopup)?.open('bottom');
  const close = () => unref(sysUserPopup)?.close();
  const sysUserListRef = ref<SysUserResult[]>([]);

  provide('api', sysUserList);
  const [register, { addData }] = useConList();

  function handleScrollToLower() {
    addData();
  }

  const tempSelected = ref<number[]>([]);

  function showUniPopup(list: number[]) {
    tempSelected.value = cloneDeep(list);
    open();
  }

  function changeChecked(systemUserId: number) {
    if (tempSelected.value.includes(systemUserId)) {
      tempSelected.value = tempSelected.value.filter((item) => item !== systemUserId) as number[];
    } else {
      tempSelected.value.push(systemUserId);
    }
  }

  function submitSelected() {
    const list = cloneDeep(tempSelected.value);
    formSettingRef.value?.submitSelected(list);
    close();
    tempSelected.value = [];
  }

  const stepBarCurrent = ref(0);
  const stepBarList = ref<string[]>(['创建表单', '添加题目', '设置发布']);
  const isScrollLoading = ref(false);

  /** 上一步 */
  function handlePreviousStep() {
    if (stepBarCurrent.value === 0) return;
    isScrollLoading.value = true;
    nextTick(() => {
      stepBarCurrent.value--;
    });
  }

  /** 下一步 / 提交 */
  async function handleSubmit() {
    switch (unref(stepBarCurrent)) {
      case 0:
        // 创建表单基础信息
        const res = await formInfoRef.value?.submit?.();
        const { serviceTicketFormId, title, details } = res as ServiceTicketFormAddData;
        if (detailRef.value) {
          detailRef.value.title = title;
          detailRef.value.details = details;
        } else {
          const r = await serviceTicketFormTemplateDetail(serviceTicketFormId as number);
          detailRef.value = r;
        }
        break;
      case 1:
        // 创建表单题目信息
        await addFormItemRef.value?.submit?.();
        break;
      case 2:
        // 表单设置
        await formSettingRef.value?.submit?.();
        uni.showModal({
          title: '保存成功',
          content: '表单保存成功，是否要立即开放填写？',
          confirmText: '开放填写',
          confirmColor: '#2878FF',
          cancelText: '暂不开放',
          cancelColor: '#999996',
          success: ({ confirm }) => {
            if (confirm && detailRef.value) {
              serviceTicketFormOpenSet({
                serviceTicketFormId: detailRef.value.id,
                status: ServiceFormStatusEnum.Up,
              });
              redirectTo({
                name: 'createServiceFormResult',
                options: {
                  serviceTicketFormId: detailRef.value.id,
                  title: detailRef.value.title,
                },
              });
            } else {
              navigateBack();
            }
          },
        });
        break;
    }
    if (stepBarCurrent.value !== stepBarList.value.length - 1) {
      isScrollLoading.value = true;
      nextTick(() => {
        stepBarCurrent.value++;
      });
    }
  }

  const handleScroll = (e: any) => {
    if (
      e.detail.scrollLeft === 0 ||
      parseInt(e.detail.scrollLeft) === uni.getWindowInfo().windowWidth * stepBarCurrent.value
    ) {
      isScrollLoading.value = false;
    }
  };
</script>

<style lang="scss" scoped>
  .action-area {
    display: flex;
    width: 100vw;
    &__item {
      flex-shrink: 0;
      width: 100vw;
      height: 100%;
      position: relative;
    }
  }

  .modal-view {
    position: fixed;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    z-index: 9999;
  }

  .popup-title {
    color: #333;
    font-size: 32rpx;
    .ali-icon {
      font-size: 40rpx;
      color: #c8cacc;
    }
  }

  .popup-warning {
    background-color: #fff4e7;
    font-size: 28rpx;
    color: #ea5e0e;
    .ali-icon {
      font-size: 36rpx;
    }
  }
  .shrink0 {
    flex-shrink: 0;
  }
  .check-box {
    width: 48rpx;
    .ali-icon {
      font-size: 40rpx;
      color: #999996;
    }
  }
</style>
